<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.brandName" placeholder="品牌名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <!--表格内容-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="brandId" sortable="custom" align="center" width="80" :class-name="getSortClass('brandId')">
        <template slot-scope="{row}">
          <span>{{ row.brandId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌名" prop="brandName" sortable="custom" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.brandName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="LOGO" align="center" width="100">
        <template slot-scope="{row}">
          <img v-if="row.brandImage" :src="row.brandImage" style="width: 50px; height: 50px;" />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 修改的表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px;">
        <el-form-item label="品牌ID">
          <el-input v-model="temp.brandId" readonly />
        </el-form-item>
        <el-form-item label="品牌名" prop="brandName">
          <el-input v-model="temp.brandName" placeholder="请输入品牌名" />
        </el-form-item>
        <el-form-item label="品牌LOGO">
  <el-upload
    class="avatar-uploader"
    action="/api/shop/brand/upload"
    :headers="{'brandId': temp.brandId}" 
    :show-file-list="false"
    :on-success="handleUploadSuccess"
    :before-upload="beforeUpload"
  >
    <img v-if="temp.brandImage" :src="temp.brandImage" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findPage, addBrand, updateBrand, deleteBrand, findAllList } from '@/api/brand'
import waves from '@/directive/waves' // waves directive
import moment from 'moment'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null, // 表格集合数据
      total: 0, // 总条数
      listLoading: true,
      listQuery: { // 查询的筛选条件
        page: 1,
        limit: 20,
        brandId: undefined,
        brandName: undefined
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      showReviewer: false,
      temp: { // 修改信息
        brandId: undefined,
        brandName: "",
        brandImage: "", // 存储的是图片 URL 或者文件路径
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        brandName: [{ required: true, message: '品牌名不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() { // 未渲染之前 data加载之后
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true;
      findPage(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        setTimeout(() => {
          this.listLoading = false;
        })
      })
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === 'id') {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id';
      } else {
        this.listQuery.sort = '-id';
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        brandId: undefined,
        brandName: "",
        brandImage: "", // 确保每次创建新的时候都清空 brandImage
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addBrand(this.temp).then(response => {
            this.dialogFormVisible = false;
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            });
            this.getList();
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          updateBrand(tempData).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            });
            this.getList();
          });
        }
      });
    },
    handleDelete(row, index) {
      deleteBrand(row.brandId).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        });
        this.getList();
      });
    },
    handleFetchPv(pv) {
      // Implement if needed
    },
    handleUploadSuccess(response, file) {
      if (response && response.url) {
        this.temp.brandImage = response.url; // 更新 brandImage 属性为服务器返回的图片 URL
      } else {
        this.$message.error('上传失败，请稍后再试');
      }
      this.getList()
    },
    beforeUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }

      return isJPGorPNG && isLt2M;
    },
    getSortClass(key) {
    const sort = this.listQuery.sort;
    if (sort === `+${key}`) {
      return 'ascending';
    } else if (sort === `-${key}`) {
      return 'descending';
    }
    return '';
  }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>